<?php

namespace backend\controllers;

use common\models\Img;
use Yii;
use backend\models\User;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;


/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        echo phpinfo();die;
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    public function actionTest()
    {
        return $this->render('test');
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {

        $model = new User();
        if (Yii::$app->request->post()) {
            $data = Yii::$app->request->post();
            $user_data = $data['User'];
            $model->username = $user_data['username'];
            $model->password_hash = $user_data['password_hash'];
            $model->mobile = $user_data['mobile'];
            if ($model->save(false)){
                $img_ids = $data['img_id'];
                if (!empty($img_ids)) {
                    foreach ($img_ids as $img_id) {
                        $img = Img::findOne($img_id);
                        $img->user_id = $model->attributes['id'];
                        $img->save(false);
                    }
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            return $this->render('create', [
                'imgs' => '',
                'model' => $model,
                'img_id' => "",
            ]);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $imgs = Img::find()->select('img_url,id')->where(['user_id' => $id])->asArray()->all();
        foreach ($imgs as $img) {
            $url = $img['img_url'];
            $imgae[] = Yii::$app->params['upload'] . $url;
            $imgId[] = ['key' => $img['id']];
//            echo "<pre/>";
//            var_dump($imgae);
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $user_data = $data['User'];
            $model->username = $user_data['username'];
            $model->password_hash = $user_data['password_hash'];
            $model->mobile = $user_data['mobile'];
            $model->gender = $user_data['gender'];
            if ($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
        return $this->render('update', [
            'model' => $model,
            'imgs' => $imgae,
            'img_id' => $imgId,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionDeleteUpload()
    {
        $id = Yii::$app->request->post('key');
        $mode = Img::findOne($id);
        if ($mode->delete()){
            $re = ['status' => 1, 'message' => '成功'];
        }else{
            $re = ['status' => 2, 'message' => '失败'];
        }
        echo json_encode($re);
    }


    /**
     *    文件上传
     *  我们这里上传成功后把图片的id进行返回
     */
    public function actionUpload ()
    {
        $model = new Img();
        if (Yii::$app->request->isPost) {
            //文件上传存放的目录
            $dir = Yii::getAlias('@backend').'/web/uploads/';
            $baseName = $_FILES['User']['name']['image'];
            $extension = $_FILES['User']['tmp_name']['image'];
            if ($model->validate()) {
                //文件名
                $fileName = $dir.$baseName;
                $results = move_uploaded_file($extension,$fileName);
                if ($results){
                    $model->img_url = $baseName;
                    if ($model->save()){
                        return $model->attributes['id'];
                    }
                }
            }
        }
        return "什么玩意";
    }

    public function actionVideo()
    {
        return $this->render('Video');
    }
}
